package com.olah.ws.controller;

import com.olah.common.entity.dto.UtilResponse;
import com.olah.common.entity.po.msg.system.SystemAddFriendMsg;
import com.olah.common.entity.po.msg.system.SystemMsg;
import com.olah.common.entity.po.msg.system.SystemMsgType;
import com.olah.common.entity.po.ws.dto.add_friend.AddFriendRequest;
import com.olah.common.entity.po.ws.dto.add_friend.AddFriendResponse;
import com.olah.common.entity.po.ws.dto.core.WebSocketRequest;
import com.olah.ws.service.SystemMsgService;
import com.olah.ws.service.PrivateMsgService;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import static com.olah.ws.service.WebSocketService.notifySystemMsg;

/**
 * Add Friend Controller
 */
@RefreshScope
@RestController
@RequestMapping("/ws/friend")
public class AddFriendController {

    @Resource
    private SystemMsgService systemMsgService;

    @Resource
    private PrivateMsgService userMsgService;

    /**
     * 添加好友申请
     * @param request 申请内容
     */
    @PostMapping("/request")
    public UtilResponse<Boolean> addFriend(@RequestBody WebSocketRequest<AddFriendRequest> request) {
        SystemAddFriendMsg<AddFriendRequest> msg = new SystemAddFriendMsg<>(request.getSender(), request.getData());
        SystemMsg systemMsg = systemMsgService.newSystemMsg(request.getReceiver().getId(), msg, SystemMsgType.ADD_FRIEND_REQUEST);
        notifySystemMsg(request.getReceiver().getId(), "有人申请添加你为好友", systemMsg, "addFriendRequest");
        return UtilResponse.success("申请发送成功", true);
    }

    /**
     * 添加好友反馈, 添加成功之后双方进行问候
     * @param response 反馈
     */
    @PostMapping("/response")
    public UtilResponse<Boolean> joinResponse(@RequestBody WebSocketRequest<AddFriendResponse> response) {
        SystemAddFriendMsg<AddFriendResponse> joinMsg = new SystemAddFriendMsg<>(response.getSender(), response.getData());
        SystemMsg systemMsg = systemMsgService.newSystemMsg(response.getReceiver().getId(), joinMsg, SystemMsgType.ADD_FRIEND_RESPONSE);
        if (response.getData().getResult()) {
            systemMsgService.joinProject(response.getReceiver().getId(), response.getData().getId());
            notifySystemMsg(response.getReceiver().getId(), response.getSender().getName() + "接受了你的好友申请", systemMsg, "addFriendResponse");
            userMsgService.doSayHello(response, userMsgService);
        } else {
            notifySystemMsg(response.getReceiver().getId(), response.getSender().getName() + "拒绝了你的好友申请", systemMsg, "addFriendResponse");
        }
        return UtilResponse.success("反馈成功", true);
    }

}
